package ua.pp.bizon.cripto.spring;

import org.springframework.context.Lifecycle;

import ua.pp.bizon.cripto.authorization.UI;
import ua.pp.bizon.cripto.configuration.Configuration;
import ua.pp.bizon.cripto.keystore.CryptoException;
import ua.pp.bizon.cripto.keystore.CryptoUtil;
import ua.pp.bizon.cripto.utils.ExceptionHandler;

public class LifeCycleImpl implements Lifecycle, Runnable {

    private Configuration configuration; // = support.getBean("configuration",
                                         // Configuration.class);
    private CryptoUtil util; // = support.getBean("cryptoUtil",
                             // CryptoUtil.class);
    private ExceptionHandler handler;

    private UI ui;

    private Thread thread;

    @Override
    public void start() {
        thread = new Thread(this);
        thread.start();
    }

    @Override
    public void stop() {
        try {
            thread.join();
        } catch (InterruptedException e) {
            handler.handle(e);
        }
        ui.done();
        System.exit(0);
    }

    @Override
    public boolean isRunning() {
        return thread.isAlive();
    }

    @Override
    public void run() {
        try {
            util.process(configuration);
        } catch (CryptoException e) {
            handler.handle(e);
        }

    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public CryptoUtil getUtil() {
        return util;
    }

    public void setUtil(CryptoUtil util) {
        this.util = util;
    }

    public ExceptionHandler getHandler() {
        return handler;
    }

    public void setHandler(ExceptionHandler handler) {
        this.handler = handler;
    }

    public UI getUi() {
        return ui;
    }

    public void setUi(UI ui) {
        this.ui = ui;
    }

    public Thread getThread() {
        return thread;
    }

    public void setThread(Thread thread) {
        this.thread = thread;
    }

}
